<html>

<head>
    <title>计算和侦听</title>
    <script src="./node_modules/vue/dist/vue.global.js"></script>
</head>

<body>
    <div id="app">
        <ul>
            <li v-for="item in items">
                产品:{{item.product}} 价格:{{item.price}} 库存:{{item.stock}} 数量:<input type="number" v-model="item.number">
            </li>
        </ul>
        <li>总价:{{total}}</li>
        <li v-html="message"></li>
        </ul> 
    </div>
    <script>
        const { createApp } = Vue;
        const app = createApp({
            el: '#app',
            data() {
                return {
                    items: [
                        { product: 'xiaomi', price: 1000, stock: 10, number: 3 },
                        { product: 'huawei', price: 2000, stock: 5, number: 2 },
                        { product: 'oppo', price: 1500, stock: 3, number: 1 }
                    ],
                    message:''
                }
            },
            computed: {
                total: function () {
                    var sum = 0;
                    for (var i = 0; i < this.items.length; i++) {
                        sum += this.items[i].price * this.items[i].number;
                    }
                    return sum;
                }
            },
            watch: {
                total: function (newVal, oldVal) {
                    console.log('total changed from ' + oldVal + ' to ' + newVal);
                },
                items: {
                    handler: function (newVal, oldVal) {
                        this.message='';
                        this.items.forEach(item => {
                            if (item.stock < item.number) {
                                this.message += '库存不可超过' + item.stock + '<br>';
                            }

                        });
                    },
                    deep: true
                }
            } 
        }  );
        // 绑定到 View
        app.mount('#app');
    </script>
</body>

</html>